#include <iostream>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
private:
    int diameter = 0;
    int search(TreeNode* node) {
        if (node == nullptr) {
            return 0;
        }
        int left = search(node->left);
        int right = search(node->right);
        diameter = max(diameter, left + right);
        return max(left, right) + 1;
    }
public:
    int diameterOfBinaryTree(TreeNode* root) {
        search(root);
        return diameter;
    }
};